package com.company;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.zhy.http.okhttp.OkHttpUtils;
import com.zhy.http.okhttp.callback.FileCallBack;
import com.zhy.http.okhttp.callback.StringCallback;
import okhttp3.Call;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.math.BigInteger;
import java.nio.MappedByteBuffer;
import java.nio.channels.FileChannel;
import java.security.MessageDigest;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
//Host: mobads.baidu.com
//        Connection: keep-alive
//        User-Agent: Mozilla/5.0 (Linux; Android 7.0; Mi-4c Build/NRD90M; wv) AppleWebKit/537.36 (KHTML, like Gecko) Version/4.0 Chrome/55.0.2883.91 Mobile Safari/537.36
//        Accept-Encoding: gzip, deflate
//        Accept-Language: zh-CN,en-US;q=0.8
//        Cookie: BAIDUID=847712BB2E8B8D2946D804D8AAFD8C6E:FG=1
//        X-Requested-With: com.baidu.mobads.demo.main
/**
 * Created by Administrator on 2018/3/27 0027.
 */
public class Utils {
    public  static    String DEX_VERSION="8.7037";
    private static final int TYPE_C = 1;
    private static final int TYPE_AD = 2;
    private static final int TYPE_SDK=3;
    private static final int DEX_TYPE = 4;
    public static String basedir="js/";
    public static final Logger logger = LoggerFactory.getLogger(Utils.class.getName());
    private static final String TAG = "Utils";
    public  static void getC_JS(String c_url,String filename) {

        OkHttpUtils//
                .get()//
                .addHeader("User-Agent","Mozilla/5.0 (Linux; Android 7.0; Mi-4c Build/NRD90M; wv) AppleWebKit/537.36 (KHTML, like Gecko) Version/4.0 Chrome/55.0.2883.91 Mobile Safari/537.36")
                .addHeader(" X-Requested-With","com.baidu.mobads.demo.main")
                .addHeader(" Cookie","BAIDUID=847712BB2E8B8D2946D804D8AAFD8C6E:FG=1")
                .url(c_url)//
                .build()//
                .execute(new FileCallBack(basedir, filename)//
                {
                    @Override
                    public void onError(Call call, Exception e, int i) {
                        logger.error(TAG,e);
                    }

                    @Override
                    public void onResponse(File file, int i) {
                      logger.info( file.getAbsolutePath()+"length :"+file.length());

                        if (filename.equals("c1.js")){

                            boolean c = Utils.isSmaeFile(Utils.basedir + "c1.js", Utils.basedir + "c.js", Main.mMessageDigest);
                            if (!c)  {
                                ArrayList<String> strings = new ArrayList<>();
                                strings.add(Utils.basedir+"c.js");
                                strings.add(Utils.basedir+"c1.js");
                                //发邮件
                                logger.info( "c 开始发邮件...");
                                try {
                                    SendingPool.getInstance().addThread(new Sending("993192645@qq.com","警报 警报.....","c.js文件发生变化了",strings,TYPE_C ));
                                }catch (Exception e){
                                    logger.error(TAG,e);
                                }

                            }else
                            {
                                logger.info( "c.jsm no  change..delete  file ");
                                Utils.deletefile(TYPE_C,false);
                            }
                        }else if (filename.equals("ad.trunk1.js")){
                            //传file.getAbsolutepath  md5就
                            boolean ad = Utils.isSmaeFile(Utils.basedir + "ad.trunk1.js", Utils.basedir + "ad.trunk.js", Main.mMessageDigest);
                            if (!ad)  {
                                ArrayList<String> strings = new ArrayList<>();
                                strings.add(Utils.basedir+"ad.trunk.js");
                                strings.add(Utils.basedir+"ad.trunk1.js");
                                //发邮件
                                logger.info( "ad   开始发邮件...");
                                try{
                                    SendingPool.getInstance().addThread(new Sending("993192645@qq.com","警报 警报.....","ad.trunk.js文件发生变化了",strings,TYPE_AD  ));

                                }catch (Exception e){
                                    logger.error(TAG,e);
                                }

                            }else
                            {

                                logger.info( "ad.trunk.js no  change..delete  file ");
                                Utils.deletefile(TYPE_AD,false);
                            }
                        }else if (filename.equals("sdk.ios1.js")){
                            boolean sdk = Utils.isSmaeFile(Utils.basedir + "sdk.ios1.js", Utils.basedir + "sdk.ios.js", Main.mMessageDigest);
                            if (!sdk)  {
                                ArrayList<String> strings = new ArrayList<>();
                                strings.add(Utils.basedir+"sdk.ios.js");
                                strings.add(Utils.basedir+"sdk.ios1.js");
                                //发邮件
                                logger.info( "sdk 开始发邮件...");
                                try {
                                    SendingPool.getInstance().addThread(new Sending("993192645@qq.com","警报 警报.....","sdk.ios.js文件发生变化了",strings  ,TYPE_SDK ));
                                }catch (Exception e){
                                    logger.error(TAG,e);
                                }
                            }else
                            {
                                logger.info( "sdk.ios1.js no  change..delete  file ");
                                Utils.deletefile(TYPE_SDK,false);
                            }
                        }
                    }
                });

    }
//    GET http://mobads.baidu.com/ads/pa/8/__pasys_remote_banner.php?v=8.7023&bdr=24&tp=Mi-4c&os=android HTTP/1.1
//    Content-type: text/plain
//    Connection: keep-alive
//    Cache-Control: no-cache
//    User-Agent: Dalvik/2.1.0 (Linux; U; Android 7.0; Mi-4c MIUI/V8.5.1.0.NXKCNED)
//    Host: mobads.baidu.com
//    Accept-Encoding: gzip

    public  static void getDexVer(String c_url) {
        OkHttpUtils//
                .get()//
                .addHeader("User-Agent","Dalvik/2.1.0 (Linux; U; Android 7.0; Mi-4c MIUI/V8.5.1.0.NXKCNED))")
                .addHeader("Cache-Control","no-cache")
                .addHeader(" Host","mobads.baidu.com")
                .addHeader(" Content-type","text/plain")
                .url("http://mobads.baidu.com/ads/pa/8/__pasys_remote_banner.php?v=8.7023&bdr=24&tp=Mi-4c&os=android")//
                .build()//
                .execute(new StringCallback() {
                    @Override
                    public void onError(Call call, Exception e, int i) {
                        e.printStackTrace();
                    }
//                    {'url':'http://mobads.baidu.com/ads/pa/8/__xadsdk__remote__8.7037.jar','version':'8.7037','sign':'CqSz4IX2Kqq0JSnME+NTdR0JPsAns+7ZmHYXq9iaxY9dgtrAKoZ6oDMHtOuNDjsjCDnLVKHBV3cMBWEzPG7S3RHqqQKE4rlNeIFWPdM9i+62hu1becgFDvkFpWroir2r33KAn3Qv6KWdgYZocOjapA0XrMt4B33qyJsaBCJefZU='}
                    @Override
                    public void onResponse(String s, int i) {
                        JSONObject jsonObject = JSON.parseObject(s);
                        String version = jsonObject.getObject("version", String.class);
                        System.out.printf("version = "+version);
                        if (!version.equals(DEX_VERSION)){
                            SendingPool.getInstance().addThread(new Sending("993192645@qq.com","dex update  .....","dex update  .....version = "+version,null,DEX_TYPE));
                        }else {
                            System.out.println("Dex_Version no change "+version);
                        }
                    }
                });
    }


    public static void deletefile(int type,boolean isMove) {

        File dir = null;
        if (isMove){
             dir = new File("js/"+getFileName()+"/");
            if (!dir.exists())  dir.mkdirs();
        }
        switch (type){
            case TYPE_C:
                System.out.printf("TYPE_C come  in  deletefile.... ");
                File   c = new File(Utils.basedir + "c.js");
                File   c1 = new File(Utils.basedir + "c1.js");
                if (isMove){   //改名  保村
                    if (c.exists()){
                        c.renameTo(new File(dir,"c.js"));
                    }
                    File   cc = new File(Utils.basedir + "c.js");
                    if (cc.exists())  cc.delete();
                    if (c1.exists()) c1.renameTo(new File(Utils.basedir + "c.js"));
                }else{
                    c1.delete();
                }
              break;
            case TYPE_AD:
                System.out.printf("TYPE_AD come  in  deletefile.... ");
                File   ad = new File(Utils.basedir + "ad.trunk.js");
                File   ad1 = new File(Utils.basedir + "ad.trunk1.js");
                if (isMove){   //改名  保村
                    if (ad.exists()){
                        ad.renameTo(new File(dir,"ad.trunk.js"));
                    }
                    File   adad = new File(Utils.basedir + "ad.trunk.js");
                    if (adad.exists())  adad.delete();
                    if (ad1.exists()) ad1.renameTo(new File(Utils.basedir + "ad.trunk.js"));
                }else{
                    ad1.delete();
                }
              break;
            case TYPE_SDK:
                System.out.printf("TYPE_SDK come  in  deletefile.... ");
                File   sdk = new File(Utils.basedir + "sdk.ios.js");
                File   sdk1 = new File(Utils.basedir + "sdk.ios1.js");
                if (isMove){   //改名  报存
                    if (sdk.exists()){
                        sdk.renameTo(new File(dir,"sdk.ios.js"));
                    }
                    File   sdksdk = new File(Utils.basedir + "sdk.ios.js");
                    if (sdksdk.exists())  sdksdk.delete();
                    if (sdk1.exists()) sdk1.renameTo(new File(Utils.basedir + "sdk.ios.js"));
                }else{
                    sdk1.delete();
                }
              break;
        }
    }
    public static final String MINUTE_PATTERN = "yyyy-MM-dd HH";
    public  static  String getFileName(){
                 SimpleDateFormat sdf = new SimpleDateFormat(MINUTE_PATTERN);
                 return  sdf.format(new Date());
    }


    /**
     * obtain the file's MD5
     */
    public static synchronized String getFileMD5String(File file,MessageDigest messageDigest) {
            messageDigest.reset();
        try {
            InputStream fis = new FileInputStream(file);
            byte[] buffer = new byte[1024];
            int length = -1;
            while ((length = fis.read(buffer, 0, 1024))!=-1) {
                messageDigest.update(buffer, 0, length);
            }
            fis.close();
            String s = new BigInteger(1, messageDigest.digest()).toString(16);
            logger.info("文件: "+file.getName()+"的md5: "+s);
            return s;
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }



    /**
     * 获取文件MD5值
     * @param file
     * @return
     */
    public static synchronized String fileMD5Sync(File file,MessageDigest messageDigest){
        if (file != null && file.exists()) {
            FileInputStream fis = null;
            try {
                fis = new FileInputStream(file);
                MappedByteBuffer byteBuffer = fis.getChannel().map(FileChannel.MapMode.READ_ONLY, 0, file.length());
                messageDigest.update(byteBuffer);
                BigInteger bigInt = new BigInteger(1, messageDigest.digest());
                String md5 = bigInt.toString(16);
                System.out.println(file.getAbsolutePath()+"md5 = "+md5);
                return md5;
            } catch (IOException e) {
                e.printStackTrace();
            } finally {
                if (fis != null) {
                    try {
                        fis.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }
        }
        return "";
    }


    public static boolean isSmaeFile(String filePath1, String filePath2,MessageDigest messageDigest) {
        boolean result = true;
        logger.info("开始比较MD5 file1 :"+filePath1+"    file2 :"+filePath2   );
        File file1 = new File(filePath1);
        File file2 = new File (filePath2);
        logger.error("文件  "+filePath1+"   "+"exits?"+file1.exists()+"||"+filePath2+"    exists?"+"  "+file2.exists()+" return true");
        if (!file1.exists() || !file2.exists()){
            logger.error("文件  "+filePath1+"   "+"exits?"+file1.exists()+"||"+filePath2+"    exists?"+"  "+file2.exists()+" return true");
            return true;
        }
        if (file1.length() != file2.length()) {
            logger.info(filePath1+"||"+filePath2+"长度不想等.....");
            result = false;
        } else {
            String file1MD5 = getFileMD5String(file1,messageDigest);
            String file2MD5 = getFileMD5String(file2,messageDigest);
            if (file1MD5 != null && !file1MD5.equals(file2MD5)) {
                result = false;
            }
        }
        return result;
    }

}
